#encoding:UTF-8
from tornado import ioloop, web
import tornado
import tornado.options
import MySQLdb
import json
import md5
import urllib
import lib
import pdb
import time
from datetime import date
import datetime
from time import mktime
conn = lib.create_conn()
CONFIG_MIEN = {
                1: "Miền Bắc",
                2: "Miền Trung",
                3: "Miền Nam"
             }

TIME_CONFIG_LOG = {
                   1:23,
                   2:23,
                   3:23
                   }


def get_info_today():
    global conn
    result = []
    for i in range(1,4):
        buf = {}
        buf['id_area'] = i
        cmd = "CALL get_info_giai('%s')" % i
        info = lib.get_result_sql(conn, cmd)
        buf1 = []
        for i in info:
            info_i = {}
            info_i['id_type'] = i['id_type']
            info_i['name_type'] = i['name_type']
            info_i['rate'] = i['rate']
            info_i['limit_number'] = i['limit_number']
            info_i['range'] = i['range']
            buf1.append(info_i)
        buf['data'] = buf1
        result.append(buf)    
    return json.dumps(result)
CONFIG_INFO = get_info_today()       

class XosoHandler(web.RequestHandler):
    def getresult(self):
        try:
            global conn
            id_area = self.get_argument('id_area')
            date = self.get_argument('date')
            result = {}
            result['date'] = lib.get_current_date(date) 
            result['id_area'] = id_area
            cmd = "CALL get_result('%s','%s')" % (date,id_area)
            dict_info = lib.get_result_sql(conn, cmd)
            result_info = [] 
            for i in dict_info:
                buf = {}
                buf['name_district'] = i['tentinh']
                buf['id_district'] = i['id_tinh']
                buf['result'] = json.loads(i['ketqua'])
                result_info.append(buf)
            
            result['data'] = result_info
            self.write(json.dumps(result))
            self.finish()
        except:
            result = {}
            result['error_code'] = 1
            result['msg'] = 'Loi client gui len khong dung'
            self.write(json.dumps(result))
            self.finish() 
    
    def getinfotoday(self):
        try:
            global conn
            global CONFIG_INFO
            result = CONFIG_INFO[:]
            result = json.loads(result)
            for i in range(1,4):
                cmd = "CALL get_info_district_today('%s','%s')" % (i,lib.get_timeunix_today())
                info = lib.get_result_sql(conn, cmd)
                buf_tinh = []
                for j in info:
                    buf = {}
                    buf['id_district'] = j['id_tinh']
                    buf['name_district'] = j['tentinh']
                    buf_tinh.append(buf)
                result[i-1]['districts'] = buf_tinh
            self.write(json.dumps(result))
            self.finish()
        except:
            result = {}
            result['error_code'] = 1
            result['msg'] = 'Loi client gui len khong dung'
            self.write(json.dumps(result))
            self.finish()
    
    def playlode(self):
        myresult = {}
        try:
            global conn
            user = self.get_argument('id_user')
            area = int(self.get_argument('id_area'))
            district = int(self.get_argument('id_district'))
            my_type = int(self.get_argument('id_type'))
            price = int(self.get_argument('price'))
            card = self.get_argument('play_card')
            time_at_now = int(time.time())
            mydate = date.today()
            current_date = int(mktime(mydate.timetuple()))
            queryInsert = "CALL insert_play_card_log('%s','%s','%s','%s','%s','%s','%s','%s')" % \
                    (user,area,district,my_type,card,current_date,price,time_at_now)
            print queryInsert
            if datetime.datetime.now().hour < TIME_CONFIG_LOG[area]:
                lib.get_result_sql(conn, queryInsert)
                myresult['code'] = 0
                myresult['msg'] = "Thành công!"
                self.write(json.dumps(myresult))
                self.finish()
                print "Insert thanh cong vao nguoi choi lo de"
            else:
                myresult['error_code'] = 1
                myresult['msg'] = "Đã quá thời gian quy định để chơi. Bạn không được chơi!"
                self.write(json.dumps(myresult))
                self.finish()
        except:
            result = {}
            result['error_code'] = 1
            result['msg'] = 'Loi Khac'
            self.write(json.dumps(result))
            self.finish()
    
    def gettransaction(self):
        global conn
        try:
            num = self.get_argument('num')
            get = self.get_argument('get')
            getTransaction = "CALL get_all_transaction('%s','%s')"%(num,get)
            allTran = lib.get_result_sql(conn, getTransaction)
            mgsArr = []
            for tran in allTran:
                user = str(tran['id_user'])
                nameType = str(tran['name_type'])
                ngayChoi = str(tran['ngay'])
                tinh = str(tran['tentinh'])
                price = str(tran['price'])
                status = str(tran['status'])
                time_at_now = int(tran['time_at_now'])
                playCard = json.loads(str(tran['play_card']))
                for card in playCard:
                    buf = {}
                    myMgs = "%s đánh $%sK - %s : %s - Xổ số tỉnh %s ngày %s" % \
                        (user,price,nameType,card,tinh,lib.get_datetime(ngayChoi))
                    buf['text'] = myMgs
                    time_play_before = (int(time.time()) - int(time_at_now)) / 60
                    str_buf = str(time_play_before) + ' phút'
                    buf['info'] = str_buf
                    buf['staus'] = status
                    mgsArr.append(buf)
            self.write(json.dumps(mgsArr))
            self.finish()
        except:
            result = {}
            result['error_code'] = 1
            result['msg'] = 'Loi Khac'
            self.write(json.dumps(result))
            self.finish()
    def getmytransaction(self):
        global conn
        try:
            user = self.get_argument('id_user')
            num = self.get_argument('num')
            get = self.get_argument('get')
            getTransaction = "CALL get_my_transaction('%s','%s','%s')"%(user,num,get)
            myTran = lib.get_result_sql(conn, getTransaction)
            mgsArr = []
            for tran in myTran:
                nameType = str(tran['name_type'])
                ngayChoi = str(tran['ngay'])
                tinh = str(tran['tentinh'])
                price = str(tran['price'])
                status = str(tran['status'])
                playCard = json.loads(tran['play_card'])
                for card in playCard:
                    buf = {}
                    myMgs = "Đánh $%sK - %s : %s - Xổ số tỉnh %s ngày %s" % \
                        (price,nameType,card,tinh,lib.get_datetime(ngayChoi))
                    buf['text'] = myMgs
                    if int(status) == 0:
                        buf['info'] = 'Chua co ket qua'
                    if int(status) == 1:
                        buf['info'] = 'Bạn đã thắng %s' % price
                    buf['status'] = status
                    mgsArr.append(buf)
                    
            self.write(json.dumps(mgsArr))
            self.finish()
        except:
            result = {}
            result['error_code'] = 1
            result['msg'] = 'Loi Khac'
            self.write(json.dumps(result))
            self.finish()
    def get(self,path):
        if path.startswith('getresult'):
            return self.getresult()
        elif path.startswith('getinfotoday'):
            return self.getinfotoday()
        elif path.startswith('playlode'):
            return self.playlode()
        elif path.startswith('getmytransaction'):
            return self.getmytransaction()
        elif path.startswith('gettransaction'):
            return self.gettransaction()



        
